(require 'package)

;; 设置gnupg homedir 解决 packages 包找不到 gpg 密钥的问题
(setq package-gnupghome-dir "~/.emacs.d/elpa/gnupg")

;; 不允许 编译第三方包到 eln
(setq package-native-compile nil)

(setq package-archives
      '(
        ;; 清华大学源（不知道什么原因最近经常下载请求被服务器拒绝）
        ;; ("melpa" . "http://mirrors.tuna.tsinghua.edu.cn/elpa/melpa/")
        ;; ("nongnu" . "http://mirrors.tuna.tsinghua.edu.cn/elpa/nongnu/")
        ;; ("gnu" . "http://mirrors.tuna.tsinghua.edu.cn/elpa/gnu/")
        ;;("org"   . "http://mirrors.tuna.tsinghua.edu.cn/elpa/org/")

        ;; 中国科技大学
        ("gnu" . "https://mirrors.ustc.edu.cn/elpa/gnu/")
        ("melpa" . "https://mirrors.ustc.edu.cn/elpa/melpa/")
        ("nongnu" . "https://mirrors.ustc.edu.cn/elpa/nongnu/")
        ))

(package-initialize)

;; 另一种包自动安装
(defun require-package (package &optional min-version no-refresh)
  (if (package-installed-p package min-version)
    t
    (if (or (assoc package package-archive-contents) no-refresh)
      (if (boundp 'package-selected-packages)
        (package-install package nil)
        (package-install package))
      (progn
        (package-refresh-contents)
        (require-package package min-version t)))))

(defun maybe-require-package (package &optional min-version no-refresh)
  (condition-case err
    (require-package package min-version no-refresh)
    (error
      (message "Couldn't install optional package `%s': %S" package err)
      nil)))

;; 使用示例
;; (require-package 'multiple-cursors)
;; (when (maybe-require-package 'multiple-cursors)
;;   (global-set-key (kbd "C-<") 'mc/mark-previous-like-this)
;;   (global-set-key (kbd "C->") 'mc/mark-next-like-this))

(provide 'init-package)
